import { useRequest } from 'ahooks';
import {
  Button, Drawer, Space, Form, Input,
} from 'antd';

import * as APIS from '../../constants/api-constants';

interface UpdateQuestionnaireProps {
  visable: boolean,
  setVisable: (visable: boolean) => void,
  templateUuid: string,
  requestQuestionnaire: (templateUuid: string) => Promise<null>;
}

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export default ({
  visable,
  setVisable,
  templateUuid,
  requestQuestionnaire
}: UpdateQuestionnaireProps) => {
  const [form] = Form.useForm();
  /**
   * 新建问卷
   */
  const { run, loading } = useRequest((data) => ({
    url: APIS.QUESTIONNAIRE,
    method: 'POST',
    data: {
      name: data.name,
      uuid: templateUuid
    }
  }), {
    manual: true,
    onSuccess: () => {
      form.resetFields();
      requestQuestionnaire(templateUuid);
      setVisable(false);
    },
    onError: () => {
    }

  });

  return (
    <Drawer
      title="新建二级问卷"
      placement="right"
      onClose={() => { setVisable(false); }}
      visible={visable}
    >
      <Form {...layout} form={form} onFinish={(data) => { run(data); }}>
        <Form.Item
          name="name"
          label="名称"
          rules={[{ required: true, message: '输入二级标题名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button onClick={() => { setVisable(false); }}>取消</Button>
            <Button htmlType="submit" type="primary" loading={loading}>
              新建
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Drawer>
  );
};
